package com.zbj.data.jpa.config;

import com.zbj.data.jpa.datasource.DynamicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import java.util.Map;

/**
 * JPASlaveDataSourceConfig
 *
 * @author weigang
 * @create 2017-09-10
 **/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(value = "com.zbj.data.jpa.repository",
		entityManagerFactoryRef = "entityManagerFactorySecondary",
		transactionManagerRef = "transactionManagerSecondary")
public class JPASlaveDataSourceConfig {

	@Autowired
	private JpaProperties jpaProperties;

	@Autowired
	private DynamicDataSource dataSource;

	@Bean(name = "entityManagerSecondary")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactorySecondary(builder).getObject().createEntityManager();
	}

	@Bean(name = "entityManagerFactorySecondary")
	public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {
		return builder
				.dataSource(dataSource)
				.properties(getVendorProperties(dataSource))
				.packages("com.zbj.data.jpa.entity") //设置实体类所在位置
				.persistenceUnit("secondaryPersistenceUnit")
				.build();
	}

	private Map<String, String> getVendorProperties(DynamicDataSource dataSource) {
		return jpaProperties.getHibernateProperties(dataSource);
	}

	@Bean(name = "transactionManagerSecondary")
	PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
	}
}